<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .message {
            width: 500px;
            height: 500px;
            border: 1px solid;
            margin: 0 auto;
            position: relative;
        }

        .myinput {
            width: 480px;
            height: 100px;
            position: absolute;
            bottom: 50px;
        }

        .btn {
            position: absolute;
            bottom: 10px;
            right: 10px;
        }
    </style>
</head>

<body>
    <div class="message">
        <h1>简易聊天</h1>
        <ul>
            <li>今天我又摸鱼了</li>
            <li>明天我还要摸鱼</li>
            <li>摸鱼还能拿工资太棒了！！</li>
        </ul>
        <textarea class="myinput">

        </textarea>
        <button class="btn">发送</button>
    </div>
    <script src="./socket.io.js"></script>
    <script>

        // 通过socket.io建立websocket连接
        let socket = io.connect();
        let ulEle = document.querySelector("ul");
        socket.on("serveEvent",function(res){
            console.log("后端发送过来的数据",res);
            let liEle = document.createElement("li");
            liEle.innerHTML = res;
            ulEle.appendChild(liEle);
        })

        // 可以通过ajax获取数据，轮询
        let btnEle = document.querySelector(".btn");
        let myinputEle = document.querySelector(".myinput");
       
        btnEle.onclick = function () {
            let val = myinputEle.value;
            // 发送数据给服务端 
            // 等同于 trigger
            socket.emit("myevent", val);


           
        }


    </script>
</body>

</html>